<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
		<title>CC防护</title>
		<link href="../../component/pear/css/pear.css" rel="stylesheet">
	</head>
	<body class="pear-container">
		<form class="layui-form" lay-filter="filter-form-sites">
			<div class="layui-row layui-col-space10">
				<div class="layui-col-md12">
					<div class="layui-card">
						<div class="layui-card-body layui-row">
							<div class="layui-col-md6">
								<div class="layui-input-inline">
									<select name="site" id="site" lay-filter="filter-site">
										<option value="0">全局设置</option>
									</select>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</form>
		<div class="layui-row layui-col-space10">
			<div class="layui-col-md12">
				<div class="layui-card">
					<div class="layui-card-header">CC防护设置</div>
					<div class="layui-card-body">
						<div class="layui-row layui-col-space10">
							<div class="layui-col-md12">
								<form class="layui-form" lay-filter="filter-form-cc">
									<div class="layui-input-group">
										<div class="layui-input-prefix" style="padding: 9px 10px 9px 0;">状态</div>
										<input type="checkbox" id="id-cc-state" name="state" lay-skin="switch" lay-filter="filter-cc-module-state" title="ON|OFF" />
										<div class="layui-input-suffix" style="padding: 9px 0px 9px 10px;">开启后可对请求进行频率限制。</div>
									</div>
								</form>
							</div>
						</div>
						<div class="layui-row layui-col-space10">
							<div class="layui-col-md12">
								<table id="id-table-rules" lay-filter="filter-table-rules"></table>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<form class="layui-form" style="background-color:#fff;padding: 10px 15px;display: none;" lay-filter="filter-form-rule" id="id-form-rule">
			<input type="hidden" name="id" />
			<input type="hidden" name="state" />
			<div class="layui-row layui-col-space10">
				<div class="layui-col-md12">规则名称</div>
			</div>

			<div class="layui-row layui-col-space10">
				<div class="layui-col-md12">
					<input type="text" name="rule" lay-verify="required" autocomplete="off" class="layui-input" />
				</div>
			</div>

			<div class="layui-row layui-col-space10">
				<div class="layui-col-md6 layui-col-sm6">统计对象</div>
				<div class="layui-col-md3 layui-col-sm3">统计时长（秒）</div>
				<div class="layui-col-md3 layui-col-sm3">阈值（次）</div>
			</div>

			<div class="layui-row layui-col-space10">
				<div class="layui-col-md6 layui-col-sm6">
					<select name="countType">
						<option value="ip">IP</option>
						<option value="url">URL</option>
					</select>
				</div>
				<div class="layui-col-md3 layui-col-sm3">
					<input type="text" name="duration" lay-verify="required|number" autocomplete="off" class="layui-input" />
				</div>
				<div class="layui-col-md3 layui-col-sm3">
					<input type="text" name="threshold" lay-verify="required|number" autocomplete="off" class="layui-input" />
				</div>
			</div>

			<div class="layui-row layui-col-space10">
				<div class="layui-col-md12 layui-col-sm12">匹配正则表达式</div>
			</div>
			<div class="layui-row layui-col-space10">
				<div class="layui-col-md12 layui-col-sm12">
					<input type="text" name="pattern" lay-verify="" autocomplete="off" class="layui-input" />
				</div>
			</div>
		
			<div class="layui-row layui-col-space10">
				<div class="layui-col-md6 layui-col-sm6">处置动作</div>
				<div class="layui-col-md2 layui-col-sm2">自动屏蔽IP</div>
				<div class="layui-col-md4 layui-col-sm4">IP屏蔽时长（秒，0 为永久）</div>
			</div>
			<div class="layui-row layui-col-space10">
				<div class="layui-col-md6 layui-col-sm6">
					<select id="id-action" name="action" lay-filter="filter-action"></select>
				</div>
				<div class="layui-col-md2 layui-col-sm2">
					<input type="checkbox" name="autoIpBlock" lay-skin="switch" title="ON|OFF" />
				</div>
				<div class="layui-col-md4 layui-col-sm4">
					<input type="text" name="ipBlockExpireInSeconds" lay-verify="required|number" autocomplete="off" class="layui-input" />
				</div>
			</div>

			<div class="layui-row layui-col-space10">
				<div class="layui-col-md12">备注</div>
			</div>

			<div class="layui-row layui-col-space10">
				<div class="layui-col-md12">
					<div class="layui-form-text">
						<textarea name="description" placeholder="请输入备注" class="layui-textarea"></textarea>
					</div>
				</div>
			</div>

			<div class="layui-row layui-col-space10">
				<div class="layui-col-md12">
					<div style="float: right;">
						<button type="submit" class="pear-btn pear-btn-primary" lay-submit lay-filter="filter-rule-save">保存</button>
						<button type="button" class="pear-btn" lay-on="ruleCancel">取消</button>
					</div>
				</div>
			</div>
		</form>

		<script type="text/html" id="id-template-toolbar">
			<button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
				<i class="layui-icon layui-icon-add-1"></i>
				新增
			</button>
		</script>
		<script type="text/html" id="id-template-bar">
			<button class="pear-btn pear-btn-primary pear-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i></button>
			<button class="pear-btn pear-btn-danger pear-btn-xs" lay-event="remove"><i class="layui-icon layui-icon-delete"></i></button>
		</script>
		<script type="text/html" id="id-template-rule-state">
			<input type="checkbox" name="state" value="{{= d.id }}" lay-skin="switch" lay-filter="filter-rule-state" title="ON|OFF" {{= d.state == "on" ? "checked" : "" }} />
		</script>

		<script src="../../component/layui/layui.js"></script>
		<script src="../../component/pear/pear.js"></script>
		<script src="../../js/action.js"></script>
		<script>
			layui.use(['form','table','util','jquery','popup'], function() {
				var table = layui.table;
				var form = layui.form;
				var util = layui.util;
				var popup = layui.popup;
				var layer = layui.layer;
				var $ = layui.$;

				// 切换域名
				form.on('select(filter-site)', function(data) {
					getSiteConfig();
					reloadTableData();
				});

				function getSiteConfig() {
					$.get('/cc/config/get', {siteId : $('#site').val()}, function(res) {
						if (res && res.data) {
							var cc = JSON.parse(res.data);
							$('#id-cc-state').prop('checked', cc.state == 'on' ? true : false);
							form.render(null, 'filter-form-cc');
						}
					}, "json");
				}

				$(function() {
					$.get('/sites/list', {}, function(data) {
						if (data && data.data) {
							$.each(data.data, function(key, site) {
								var serverName = site.serverNames.join(',');
								$('#site').append('<option value="' + site.id + '">' + serverName + '</option>');
							});

							form.render(null, 'filter-form-sites');
							getSiteConfig();
							reloadTableData();
						}
					}, "json");

					// 阻止回车触发表单提交
					$('input').on('keydown', function (e) {
						if (e.keyCode === 13) {
							e.preventDefault();
							return false;
						}
					});
				});

				table.render({
					elem: '#id-table-rules',
					cols: [[
						{field: 'rule', title: '规则名称'},
						{field: 'state', title: '状态', templet: '#id-template-rule-state', width: 100},
						{field: 'countType', title: '统计对象', width: 100},
						{field: 'pattern', title: '匹配正则', minWidth: 60},
						{field: 'duration', title: '统计时长', templet: '<div>{{= d.duration }} 秒</div>'},
						{field: 'threshold', title: '阈值', templet: '<div>{{= d.threshold }} 次</div>'},
						{field: 'action', title: '响应动作', templet: function(d) {
							return '<div>' + getActionText(d.action) + '</div>';
						}},
						{field: 'autoIpBlock', title: '自动屏蔽IP', width: 100, templet: function(d) {
							return d.autoIpBlock == 'on' ? '是' : '否';
						}},
						{field: 'ipBlockExpireInSeconds', title: 'IP屏蔽时长', width: 100, templet: function(d) {
							if (d.ipBlockExpireInSeconds == 0) {
								return '永久';
							} else {
								return d.ipBlockExpireInSeconds + ' 秒';
							}
						}},
						{field: 'description', title: '备注', minWidth: 200},
						{fixed: 'right', title:'操作', width: 110, minWidth: 110, toolbar: '#id-template-bar'}
					]],
					toolbar: '#id-template-toolbar',
					css:'.layui-form{margin-top:0px;}',
					page: true,
					limits: [5, 10, 15, 20, 25, 30],
					limit: 10, // 每页默认显示的数量
				});

				function reloadTableData() {
					table.reloadData('id-table-rules', {
						url: '/cc/rule/list',
						page: {
							curr: 1
						},
						where: {
							siteId: $('#site').val()
						}
					});
				}

				function openLayer(title) {
					layer.open({
						type: 1,
						title: title,
						shade: 0.6,
						shadeClose: true,
						content: $('#id-form-rule'),
						end: function() {
							$("#id-form-rule").trigger("reset");
							$("#id-form-rule").find("input[type='hidden']").val("");
						}
					});
				}

				// 触发单元格工具事件
				table.on('tool(filter-table-rules)', function(obj) {
					var data = obj.data; // 获得当前行数据

					if(obj.event === 'edit') {
						openLayer('编辑规则');
						var autoIpBlock = data.autoIpBlock == 'on' ? true : false;
						data.autoIpBlock = autoIpBlock;
						form.val('filter-form-rule', data);
					} else if(obj.event === 'remove') {
						layer.confirm('确定删除该规则吗？', {
							icon: 3,
							title: '提示'
						},
						function(index) {
							var param = {siteId : $('#site').val()};
							param.ruleId = data.id;
							$.post('/cc/rule/remove',  param, function(res) {
								if (res && res.code == 200) {
									obj.del();
									table.reloadData('id-table-rules');
									layer.close(index);
									return true;
								} else {
									popup.failure(res.msg);
									return false;
								}
							}, "json");
						});
					}
				});

				table.on('toolbar(filter-table-rules)', function(obj) {
					if (obj.event === 'add') {
						openLayer('添加规则');
					} else if (obj.event === 'refresh') {
						table.reload('id-table-rules');
					}
				});

				util.on('lay-on', {
					ruleCancel: function() {
						layer.closeLast('page');
					}
				});

				// 规则提交保存事件
				form.on('submit(filter-rule-save)', function(data) {
					var field = data.field; // 获取表单字段值
					if (!field.id) {
						field.state = 'off';
					}

					if (field.autoIpBlock != 'on') {
						field.autoIpBlock = 'off';
					}

					var param = {siteId : $('#site').val()};
					param.rule = JSON.stringify(field);
					
					$.post('/cc/rule/save',  param, function(res) {
						if (res && res.code == 200) {
							table.reloadData('id-table-rules');
							layer.closeLast('page');
							popup.success("已保存");
							return true;
						} else {
							popup.failure(res.msg);
							return false;
						}
					}, "json");

					return false; // 阻止默认 form 跳转
				});

				form.on('switch(filter-rule-state)', function(obj) {
					var param = {siteId : $('#site').val()};
					param.ruleId = this.value;
					param.state = this.checked ? 'on' : 'off';

					$.post('/cc/rule/state/update',  param, function(res) {
						if (res && res.code == 200) {
							table.reloadData('id-table-rules');
							return true;
						} else {
							popup.failure(res.msg);
							return false;
						}
					}, "json");
				});

				form.on('switch(filter-cc-module-state)', function(obj) {
					var state = this.checked ? 'on' : 'off';
					var param = {siteId: $('#site').val(), state : state}
					$.post('/cc/config/state/update', param, function(data) {
						if (data && data.code == 200) {
							return true;
						} else {
							popup.failure(data.msg);
							return false;
						}
					}, "json");
				});

				$(function() {
					initActionSelect('id-action', 'coding', function() {
						form.render($('#id-action'));
					});
				});
			});

		</script>
	</body>
</html>
